﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Gun : MonoBehaviour {
    [SerializeField]
    public List<GameObject> carTargets=new List<GameObject>();
    public Transform target;
    public GameObject fire;
    public Transform shoot;
    public bool Islight = false;
    private LineRenderer Light;
    private float lightDamage=1;
    public float attackRate=1;
    public float timer = 0;
    private void OnTriggerEnter2D(Collider2D collision)
    {
        if (collision.transform.tag == "Car")
        {
            carTargets.Add(collision.gameObject);
        }
    }

    private void OnTriggerExit2D(Collider2D collision)
    {
        if (collision.tag == "Car")
        {
            carTargets.Remove(collision.gameObject);
        }
    }

    private void Start()
    {
        Light = transform.GetComponent<LineRenderer>();
        timer = attackRate;
    }

    private void Update()
    {
        LookAt();

        if(Islight==false&&carTargets.Count>0)
        {
            timer += Time.deltaTime;
            if (timer >= attackRate)
            {
                Attack();
                timer = 0;
            }
        }
        else if(carTargets.Count>0)
        {
            if (Light.enabled == false)
                Light.enabled = true;
            LightAttack();
            
        }
        if (Islight == true && carTargets.Count <= 0)
            Light.enabled = false;
    }

    private void LightAttack()
    {
        Vector3[] linepos=new Vector3[2] {shoot.position, target.position};
        Light.SetPositions(linepos);
        target.GetComponent<Car>().TakeDamage(lightDamage);
    }

    private void LookAt()
    {
       
        if (carTargets.Count > 0)
        {
            target = carTargets[0].transform;
            Vector3 direction = target.position - transform.position;
            direction.z = 0f;
            direction = direction.normalized;
            transform.up = direction;
            
        }
        else
        {
            timer = attackRate;
        }
       
    }

   // private void UpdateTargets()
   // {
   //     List<int> nullIndex = new List<int>();
   //     for (int i=0;i<carTargets.Count;i++)
   //     {
   //         if(carTargets[i]==null)
   //           nullIndex.Add(i);
   //     }

  //      for(int i=0;i<nullIndex.Count;i++)
  //      {
  //          carTargets.RemoveAt(nullIndex[i] - i);
  //      }
 //   }

    private void Attack()
    {
        GameObject obj = GameObject.Instantiate(fire, shoot.position, shoot.rotation);
        obj.GetComponent<Fire>().SetTarget(carTargets[0].transform);
        
    }
}
